package com.ly.web.controller.king;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.KingOrgEntity;
import com.ly.heart.domain.KingPurchaseTermsEntity;
import com.ly.heart.domain.king.base.BaseModelBo;
import com.ly.heart.domain.king.base.PurchaseTermsBo;
import com.ly.heart.domain.request.KingBaseRequest;
import com.ly.heart.domain.response.KingBaseResponse;
import com.ly.heart.domain.response.KingBaseResponseError;
import com.ly.heart.domain.response.KingBaseResponseSuccessEntity;
import com.ly.heart.service.IKingOrgService;
import com.ly.heart.service.IKingPurchaseTermsService;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.heart.util.KingCommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 0:22 2024-09-08
 * @return
 */
@Api (value = "PurchaseTermsRemote", tags = "推基础数据-采购条款")
@RestController
@RequestMapping ("/heart/PurchaseTermsRemote")
@Slf4j
public class PurchaseTermsRemote {

    @Resource
    private IKingPurchaseTermsService iKingPurchaseTermsService;
    @Resource
    private IKingOrgService iKingOrgService;

    /**
     * 同步拉取采购，销售条款
     * @param type：用于区分采购和销售；1：采购；2：销售
     * @return
     * @throws Exception
     */
    @ApiOperation ("同步拉取采购/销售条款列表")
    @RequestMapping ("pull")
    public AjaxResult queryList (Integer type) throws Exception {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity :: getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        String jsonData = "{\"FormId\":\"" + ( type == 1 ? KingConstUtil.BD_PURCLAUSE : KingConstUtil.BD_SALCLAUSE ) + "\",\"FieldKeys\":\"FNumber,FName,FClauseTypeId,FDocumentStatus,FClauseContent,FDescription \",\"FilterString\":[],\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
        List<List<Object>> lists = client.executeBillQuery ( jsonData );
        for ( int i = 0; i < lists.size (); i++ ) {
            List<Object> objects = lists.get ( i );
            log.info ( "-->{}", objects );
            KingPurchaseTermsEntity one = iKingPurchaseTermsService.getOne ( new LambdaQueryWrapper<KingPurchaseTermsEntity> ().eq ( KingPurchaseTermsEntity :: getCode, String.valueOf ( objects.get ( 0 ) ) ) );
            if ( one == null ) {
                one = new KingPurchaseTermsEntity ();
                one.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                one.setCode ( String.valueOf ( objects.get ( 0 ) ) );
                one.setName ( String.valueOf ( objects.get ( 1 ) ) );
                one.setTermsType ( String.valueOf ( objects.get ( 2 ) ) );
                one.setState ( String.valueOf ( objects.get ( 3 ) ).equals ( "C" ) ? "2" : "0" );
                one.setTermsContent ( String.valueOf ( objects.get ( 4 ) ) );
                one.setDescribeInfo ( String.valueOf ( objects.get ( 5 ) ) );
                one.setCreateTime ( DateUtils.getNowDate () );
                one.setType ( type );
                one.setIsSend ( 1 );
                iKingPurchaseTermsService.save ( one );
            }
        }
        return AjaxResult.success ();
    }


    @ApiOperation ("同步发送采购条款到金蝶")
    @RequestMapping ("push")
    public AjaxResult push (Integer type) throws Exception {
        KingOrgEntity orgEntity = iKingOrgService.getOne ( new LambdaQueryWrapper<KingOrgEntity> ().eq ( KingOrgEntity :: getOrgId, CurrentUserUtil.getCompanyId () ).eq ( KingOrgEntity :: getIsDisabled, false ) );
        if ( orgEntity == null ) {
            throw new CustomException ( "请先至系统管理中配置金蝶账套！" );
        }
        IdentifyInfo identifyInfo = KingCommonUtil.getIdentifyInfo ( orgEntity );
        K3CloudApi client = new K3CloudApi ( identifyInfo );
        List<KingPurchaseTermsEntity> list = iKingPurchaseTermsService.list ( new LambdaQueryWrapper<KingPurchaseTermsEntity> ().
                eq ( KingPurchaseTermsEntity :: getType, type ).
                eq ( KingPurchaseTermsEntity :: getIsUsed, ConstUtil.IS_USED_YES ).
                eq ( KingPurchaseTermsEntity :: getIsDisabled, 1 ).
                eq ( KingPurchaseTermsEntity :: getIsSend, KingConstUtil.KING_DATA_IS_SEND_NO ) );
        if ( CollectionUtils.isEmpty ( list ) ) {
            return AjaxResult.error ( "暂无新数据可推！" );
        }
        batchSave ( list, client, type );
        submit ( list, client, type );
        audit ( list, client, type );
        return AjaxResult.success ( "推送条款成功。" );
    }

    private void batchSave (List<KingPurchaseTermsEntity> list, K3CloudApi client, Integer type) throws Exception {
        KingBaseRequest request = new KingBaseRequest ();
        List<BaseModelBo> bos = new ArrayList<> ();
        list.forEach ( termsEntity -> {
            PurchaseTermsBo bo = new PurchaseTermsBo ();
            bo.setFNumber ( termsEntity.getCode () );
            bo.setFName ( termsEntity.getName () );
            bo.setFClauseContent ( termsEntity.getTermsContent () );
            bo.setFDescription ( termsEntity.getDescribeInfo () );
            bo.setFClauseTypeId ( termsEntity.getTermsType () );
            bos.add ( bo );
        } );
        request.setModel ( bos );
        String s = JSONObject.toJSONString ( request );
        log.info ( "bos-》{}", bos );
        log.info ( "s->{}", s );
        String resultJson = client.batchSave ( type == 1 ? KingConstUtil.BD_PURCLAUSE : KingConstUtil.BD_SALCLAUSE, s );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //添加成功，进行提交
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "条款-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 推送成功", sb );
            //修改为已推送状态
            list.forEach ( termsEntity -> {
                iKingPurchaseTermsService.update ( new LambdaUpdateWrapper<KingPurchaseTermsEntity> ().
                        set ( KingPurchaseTermsEntity :: getIsSend, KingConstUtil.KING_DATA_IS_SEND_YES ).
                        eq ( KingPurchaseTermsEntity :: getId, termsEntity.getId () ) );
            } );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "条款-推送失败：【" + sb + "】" );
        }
    }


    private void submit (List<KingPurchaseTermsEntity> list, K3CloudApi client, Integer type) throws Exception {
        PurchaseTermsBo bo = new PurchaseTermsBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( bankEntity -> {
            strings.add ( bankEntity.getCode () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.submit ( type == 1 ? KingConstUtil.BD_PURCLAUSE : KingConstUtil.BD_SALCLAUSE, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            //提交成功
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "条款-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.error ( "{} 提交成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "条款提交失败：【" + sb + "】" );
        }
    }

    private void audit (List<KingPurchaseTermsEntity> list, K3CloudApi client, Integer type) throws Exception {
        PurchaseTermsBo bo = new PurchaseTermsBo ();
        List<String> strings = new ArrayList<> ();
        list.forEach ( bankEntity -> {
            strings.add ( bankEntity.getCode () );
        } );
        bo.setNumbers ( strings );
        String jsonData = JSON.toJSONString ( bo );
        String resultJson = client.audit ( type == 1 ? KingConstUtil.BD_PURCLAUSE : KingConstUtil.BD_SALCLAUSE, jsonData );
        Gson gson = new Gson ();
        //对返回结果进行解析和校验
        RepoRet repoRet = gson.fromJson ( resultJson, RepoRet.class );
        KingBaseResponse baseResponse = JSONObject.parseObject ( gson.toJson ( repoRet.getResult ().getResponseStatus () ), KingBaseResponse.class );
        StringBuilder sb = new StringBuilder ();
        if ( baseResponse.getIsSuccess () == true ) {
            List<KingBaseResponseSuccessEntity> successEntities = baseResponse.getSuccessEntitys ();
            sb.append ( "条款-编码为：【" );
            successEntities.forEach ( success -> {
                sb.append ( success.getNumber () ).append ( ";" );
            } );
            sb.append ( "】" );
            log.info ( "{} 审核成功", sb );
        } else {
            List<KingBaseResponseError> errors = baseResponse.getErrors ();
            errors.forEach ( err -> {
                sb.append ( err.getMessage () ).append ( ";" );
            } );
            throw new RuntimeException ( "条款审核失败：【" + sb + "】" );
        }
    }

}
